#!/usr/bin/env bash

###### script header ######

lib=$(realpath @@BASE_LIB@@) || exit 1
stat "${lib}" >> /dev/null || exit 1

# shellcheck source=../sh/lib.bash
if ! source "${lib}"; then
  echo "Error: could not find import"
  exit 1
fi

go=$(realpath @@GO@@)
stat "${go}" >> /dev/null
govulncheck=$(realpath @@GOVULNCHECK@@)
stat "${govulncheck}" >> /dev/null
jq=$(realpath @@JQ@@)
stat "${jq}" >> /dev/null

cd "${BUILD_WORKSPACE_DIRECTORY}"

###### script body ######

submodules=$(${go} list -f '{{.Dir}}' -m)

PATH=$(dirname "${go}"):${PATH}

check_module() {
  excluded_osvs=(
    "GO-2025-3521" # Kubernetes GitRepo Volume Inadvertent Local Repository Access
    "GO-2025-3547" # Kubernetes kube-apiserver Vulnerable to Race Condition
    "GO-2025-3770" # Host Header Injection which Leads to Open Redirect in RedirectSlashes in github.com/go-chi/chi
  )

  # shellcheck disable=SC2016 # The $ sign in the single quoted string is correct.
  CGO_ENABLED=0 ${govulncheck} -C "$1" -format json "./..." |
    "${jq}" --argjson excluded "$(printf '"%s"\n' "${excluded_osvs[@]}" | jq -s)" -sr '
        (map(select(.osv) | {"key": .osv.id, "value": .osv.summary}) | from_entries) as $osvs | 
        map(select( .finding and all($excluded[] != .finding.osv; .) ) | .finding | select( .trace[-1].module | startswith("github.com/edgelesssys/") )) |
        group_by(.osv) | 
        map( {"osv": .[0].osv, "summary": $osvs[.[0].osv], "traces": [.[] | [.trace[] | .module]]} ) |
        if length > 0 then halt_error(1) else .[] end'

}

check() {
  err=0

  echo "Scanning Go vulnerability DB for known vulnerabilities in modules:"
  for mod in ${submodules}; do
    echo "  ${mod}"
    echo -n "  "
    check_module "${mod}"
  done

  exit "${err}"

}

if test -v SILENT; then
  check > /dev/null
else
  check
fi
